package com.calendar.api.controller;

import com.calendar.api.model.ApiResponse;
import com.calendar.api.model.dto.UserDTO;
import com.calendar.api.security.JwtTokenProvider;
import com.calendar.api.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Api(tags = "认证管理")
public class AuthController {

    private final UserService userService;
    private final JwtTokenProvider jwtTokenProvider;

    @Autowired
    public AuthController(UserService userService, JwtTokenProvider jwtTokenProvider) {
        this.userService = userService;
        this.jwtTokenProvider = jwtTokenProvider;
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ApiResponse<UserDTO> register(@Valid @RequestBody UserDTO userDTO) {
        return ApiResponse.success(userService.register(userDTO));
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ApiResponse<Map<String, Object>> login(@Valid @RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        
        // 验证用户凭证
        if (!userService.validateCredentials(username, userDTO.getPassword())) {
            return ApiResponse.error(401, "用户名或密码错误");
        }
        
        // 获取用户信息
        UserDTO user = userService.findByUsername(username);
        
        // 生成JWT令牌
        String token = jwtTokenProvider.createToken(username, user.getId());
        
        // 返回用户信息和令牌
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("token", token);
        responseData.put("userId", user.getId());
        responseData.put("username", user.getUsername());
        
        return ApiResponse.success(responseData);
    }

    @PostMapping("/logout")
    @ApiOperation("用户退出")
    public ApiResponse<Void> logout() {
        // JWT是无状态的，客户端只需要删除令牌即可
        // 这里可以添加令牌黑名单等逻辑
        return ApiResponse.success();
    }
} 